//import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { FileInfo } from "@/types"
import {showFailToast, showConfirmDialog} from "vant";
import axios from 'axios'
import { localStorage } from '@/utils/storage'
import _ from 'lodash'


const request = function (reqUrl:string,file:File,otherData:{}, showError=true) {
    let contextPath =import.meta.env.VITE_BASE_URL
    //兼容问题
    if(_.isEmpty(Promise.prototype.finally)) {
        Promise.prototype.finally = function (callback) {
            let Promise = this.constructor
            return this.then(
                 (value)=> {
                    // @ts-ignore
                    Promise.resolve(callback()).then(
                        ()=>{
                            return value
                        }
                    )
                },
                 (reason)=> {
                    // @ts-ignore
                    Promise.resolve(callback()).then(
                        ()=> {
                            throw reason
                        }
                    )
                }
            )
        }
    }
    return new Promise((resolve, reject)=>{
        if('http:' == document.location.protocol){   //http协议
            contextPath = contextPath.replace(/^https/,"http")
        }
        //请求头部、请求参数
        let headers:any = {}
        headers["Content-Type"] = "multipart/form-data"

        let accessToken = localStorage.get("x-auth-token")
        if(!_.isEmpty(accessToken) && accessToken !== 'null'){
            headers["x-auth-token"] = accessToken
        }
        const formData = new FormData();
        formData.append('file', file);
        if (_.isObject(otherData)) {
            _.forEach(otherData, function (val:any, key:string) {
                formData.append(key, val);
            });
        }

        axios({
            method: 'post',
            data: formData,
            timeout:30000,
            url: contextPath + reqUrl,
            headers:headers,
        }).then( (response)=> {
            if(!_.isEmpty(response.headers["x-auth-token"])){
                localStorage.set("x-auth-token",response.headers["x-auth-token"])
            }
            resolve(response.data)
        }).catch( (error)=> {
            let status:number
            let showMsg = ""
            // 【务必注意】这里的error输出的不是一个对象【error.response才是一个对象】
            if (error.response) {
                status = error.response.status;
                console.log(status+' error.response.data',error.response.data)
                console.log(status+' error.response.status',error.response.status)
                console.log(status+' error.response.headers',error.response.headers)
                // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围

            } else if (error.request) {
                // 请求已经成功发起，但没有收到响应
                console.log('502 error.request',error.request)
                status = 502
            } else {
                // 发送请求时出了点问题
                console.log('501 error.message', error.message)
                status = 501
            }
            console.log('error.config',error.config)


            if(401 == status){
                showMsg = "401 未登陆"
            } else if(403 == status){
                showMsg = "403 您没有访问权限"
            } else if(404 == status){
                showMsg = "404 请求不存在"
            } else if(400 == status){
                showMsg = "400服务器无法解析参数"
            } else if(500 == status){
                showMsg = "500 服务器异常"
            } else if(502 == status){
                showMsg = "502 服务不可用"
            } else{
                showMsg = "无效的请求: "+error.message
            }
            if(showError){
                if(401 !== status) {
                    showFailToast(reqUrl+" : "+showMsg)
                }else{
                    showConfirmDialog( {
                        title: '提示',
                        message: '当前页面已失效，请重新登录',
                    }).then(() => {
                        localStorage.clear()
                        window.location.href = '/login/'
                    });
                }
            }else{
                reject({
                    response:{code:status,msg:showMsg}
                })
            }
        })
    })
}

export default request